package com.aube.mis.interceptor;

import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.aube.mis.dto.PaginationResultDTO;
import com.aube.mis.dto.ShowDTO;
import com.aube.mis.service.ShowService;
import com.aube.mis.util.Constant;
import com.aube.mis.vo.DataTableCriterias;

public class ServletInterceptor implements HandlerInterceptor {

	private static Logger log = LoggerFactory.getLogger(ServletInterceptor.class);

	@Resource
	ShowService showService;
	
	private static final int randomVersion = randomVersion();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		HandlerMethod handler = (HandlerMethod) obj;
		log.info("[method " + handler.getMethod().getName() + " invoke]");
		long startTimeMillis = System.currentTimeMillis();
		request.setAttribute("startTimeMillis", startTimeMillis);
		if (request.getSession().getAttribute(Constant.Attr.SHOW_LIST) == null) {
			PaginationResultDTO<ShowDTO> showList = showService.getShowList(new DataTableCriterias(0, 9999));
			request.getSession().setAttribute(Constant.Attr.SHOW_LIST, showList.getResultList());
		}
		request.setAttribute(Constant.Attr.SHOW_ID, getShowId(request));
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception) throws Exception {
		HandlerMethod handler = (HandlerMethod) obj;
		long startTimeMillis = Long.parseLong(request.getAttribute("startTimeMillis").toString());
		long endTimeMillis = System.currentTimeMillis();
		log.info("[method " + handler.getMethod().getName() + " end and cost " + (endTimeMillis - startTimeMillis) + "]");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception {
		request.setAttribute("staticVersion", randomVersion);
	}

	public static int randomVersion() {
		int max = 99999;
		int min = 10000;
		Random random = new Random();
		return random.nextInt((max - min) + 1) + min;
	}

	private String getShowId(HttpServletRequest request) {
		String showId = "";
		String reqShowId = request.getParameter("showId");
		if (StringUtils.isEmpty(reqShowId)) {
			List<ShowDTO> showList = (List<ShowDTO>) request.getSession().getAttribute(Constant.Attr.SHOW_LIST);
			if (!showList.isEmpty()) {
				showId = showList.get(0).getShowId();
			}
		} else {
			showId = reqShowId;
		}
		log.info("showId=" + showId);
		return showId;
	}

}
